package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vo.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        //minBehotTime = 2063,加载页面的时候设置了一个大的时间值,比这个时间值小然后降序排列即可
        //public_time < minBehoTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadNew(ArticleHomeDto dto) {
        //public_time > maxBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);    }

    @Override
    public ResponseResult loadMore(ArticleHomeDto dto) {
        //public_time < minBehoTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Override
    public void generate(Long articleId) {
        //1.查询article_content表得到详情
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectById(wrapper);

        //1.1查询得到的数据要判空
        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        //2.将content字段提取出来,按照模板需要的格式进行赋值
        //2.1初始化要赋值
        Map<String,Object> map = new HashMap<>(1);
        //2.1JSON.parseArray(apArticleContent.getContent()),
        // content在数据库中是键值对的形式，而模板中是一个遍历集合的形式，所以要将content转为集合的形式给予模板
        map.put("content", JSON.parseArray(apArticleContent.getContent()));

        //3.调用Freemarker插件，进行HTML文件生成
        InputStream stream = freemarkerGenerator.generate("article.ftl", map);

        //4.调用minio实现文件上传
        String url = minIoTemplate.uploadFile("", articleId + ".html", stream, "html");

        //5.更新ap_article表中static_url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        //5.1对于传入或得到的将要使用的值都要进行判空
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {

        //1.传入参数判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle apArticle = new ApArticle();
        //将dto中的数据复制到apArticle中
        BeanUtils.copyProperties(dto,apArticle);

        //2.判断dto里的id是否存在
        Long id = dto.getId();
        if (id == null) {
            //3.不存在则新增文章

            //3.1插入article表,设置article表中内容
            int articleInsertResult = apArticleMapper.insert(apArticle);
            //返回0则为新增失败,1为新增成功
            if (articleInsertResult < 1) {
                log.warn("article表数据更新失败");
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            //3.2插入article_config表
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setArticleId(apArticle.getId());
            int configInsertResult = apArticleConfigMapper.insert(apArticleConfig);
            if (configInsertResult < 1) {
                log.warn("article_config表数据插入失败");
                throw new RuntimeException("article_config表数据插入失败");
            }


            //3.3插入article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(apArticle.getId());
            int contentInsertResult = apArticleContentMapper.insert(apArticleContent);
            if (contentInsertResult < 1) {
                log.warn("article_content表数据插入失败");
                throw new RuntimeException("article_content表数据插入失败");
            }

            //将新生成的id返回
            return ResponseResult.okResult(apArticle.getId());

        }else {
            //4.id存在则修改文章

            //4.1更新article表
            int articleUpdateResult = apArticleMapper.updateById(apArticle);
            if (articleUpdateResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章修改失败");
            }

            //4.2修改article_content表
            ApArticleContent content = new ApArticleContent();
            content.setContent(dto.getContent());
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            int updateContentResult = apArticleContentMapper.update(content, wrapper);
            if (updateContentResult < 1) {
                log.warn("文章内容修改失败");
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章内容修改失败");
            }
        }
        //5.将原有的id返回
        return ResponseResult.okResult(id);

    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public void sendIndexUpdate(ApArticle apArticle, String content) {
        if (apArticle == null || StringUtils.isBlank(content)) {
            log.warn("入参为空");
            return;
        }

        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);

        kafkaTemplate.send("es.index.update", JSON.toJSONString(vo));
    }

    @Override
    public ResponseResult loadBack(ArticleInfoDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"dto为空");
        }
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        if (articleId == null || authorId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"传入参数为空");
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户未登录");
        }
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }

        boolean isLike = false, isUnlike = false, isCollection = false, isFollow = false;

        Object likeResult = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
        if (likeResult != null) {
            isLike = true;
        }

        Object unlikeResult = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
        if (unlikeResult != null) {
            isUnlike = true;
        }

        Object collectionResult = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId, userId.toString());
        if (collectionResult != null) {
            isCollection = true;
        }

        Double zScore = cacheService.zScore(userId.toString(), authorId.toString());
        if (zScore != null) {
            isFollow = true;
        }
        Map<String,Object> result = new HashMap<>();
        result.put("islike",isLike);
        result.put("isunlike",isUnlike);
        result.put("iscollection",isCollection);
        result.put("isfollow",isFollow);



        return ResponseResult.okResult(result);
    }
}
